const schedule = require("node-schedule");
const { countRepoSpecDateSpan } = require("../script/countRepo");
const { getAllRepoListWithoutPaging } = require("../model/repos");
const syncRepo = require("../script/syncRepos");
const { output, mailConfig } = require("../config/config");
const { getRenderDailyTpl } = require("../script/renderDailyTpl");
const { send } = require("../script/mail");
const dayjs = require("dayjs");

/**
 * 定时统计branchId指定部门下的所有组在前一天的统计数据，并发送邮件
 * @param branchId 统计部门
 * 注意：收件人、定时时间均从配置读取
 */
module.exports.sendDaily = function (branchId) {
  console.log("日报脚本定时任务 --> ", mailConfig.taskTime);
  schedule.scheduleJob(mailConfig.taskTime, async () => {
    try {
      //nyrDate 前一天的日期
      const nyrDate = dayjs().subtract(1, "day").format("YYYY-MM-DD");
      //查指定部门的仓库
      // const reposList = await getRepoListByBranchId({
      //   branchId,
      // });
      //查询全部仓库（这些仓库会被同步+统计数据，但是发日报只发branch=1的那些数据）
      const reposList = await getAllRepoListWithoutPaging();

      //同步仓库
      await syncRepo(reposList, output);

      //统计数据
      await countRepoSpecDateSpan(
        reposList,
        nyrDate,
        nyrDate,
        "12:00:00",
        output
      );

      //生成日报
      const html = await getRenderDailyTpl(branchId, nyrDate);

      //发送日报
      await send(
        `【千寻】报价研发部-代码量统计(${nyrDate})`,
        mailConfig.sendAddress,
        html
      );

      console.log(`${nyrDate}日报发送成功`);
    } catch (err) {
      console.log("日报定时任务 err --> ", err);
    }
  });
};
